import { useCallback } from 'react'

let dragging: Record<string, any> | undefined
let spaceObject: string | null = null

export const useDrag = (
  list: Record<string, any>[],
  setList: any,
  specObj: Record<string, any>
) => {
  const handleDragStart = useCallback(
    (e: any) => {
      dragging = list.find((item: Record<string, any>) => item.id === e.currentTarget.dataset.id)
      spaceObject = null
    },
    [list]
  )
  const handleDragOver = useCallback((e: any) => {
    e.dataTransfer.effectAllowed = 'move'
    e.preventDefault()
  }, [])
  const handleDragEnter = useCallback(
    (e: any) => {
      e.dataTransfer.effectAllowed = 'move'
      e.preventDefault()
      const { id } = e.currentTarget.dataset
      if (dragging && dragging.id !== id) {
        const newItems = list.slice()
        const toIndex = newItems.findIndex((item: Record<string, any>) => item.id === id)
        const toItem = list[toIndex]
        if (spaceObject === null) {
          spaceObject = dragging.id
        }
        const src = newItems.findIndex((item: Record<string, any>) => item.id === spaceObject)
        newItems.splice(toIndex, 1, { id: spaceObject, ...specObj })
        newItems.splice(src, 1, toItem)
        setList(newItems)
      }
    },
    [list]
  )
  const handleDragEnd = useCallback(() => {
    if (dragging && spaceObject) {
      const newItems = list.slice()
      const src = newItems.findIndex((item: Record<string, any>) => item.id === spaceObject)
      newItems.splice(src, 1, dragging)
      setList(newItems)
      dragging = undefined
      spaceObject = null
    }
  }, [list])
  return {
    handleDragStart,
    handleDragOver,
    handleDragEnter,
    handleDragEnd,
  }
}